/**
 * @description doc-builder
 *
 * @author xiaomi
 */

const path = require('path');
const fsp = require('fs-extra');
const Promise = require('bluebird');

const exec = require('../lib/exec');
const logger = require('../services/logger');

module.exports = function() {
    const glob = Promise.promisify(require('glob'));

    const docsPath = path.join(__dirname, '../../docs');
    const apiControllerPath = path.join(__dirname, '../controllers/api');

    glob(apiControllerPath + '/**')
    .map(p => {
        return fsp.stat(p);
    })
    .map(stat => {
        return +stat.mtime || 0;
    })
    .then(mtimes => {
        return Math.max(...mtimes);
    })
    .then(apiControllerMTime => {
        return fsp.stat(docsPath)
        .then(stat => {
            let docsMTime = +stat.mtime;

            return docsMTime < apiControllerMTime;
        })
        // ignore this error
        .catch(() => {
            return true;
        });
    })
    .then(changed => {
        if(!changed) {
            return;
        }

        return exec('npm run docs --silent');
    })
    .then(stdout => {
        if(stdout) {
            logger.info('Doc build success');
        }
    })
    .catch(ex => {
        logger.info('Doc build error');
        logger.error(ex);
    });
};
